<template>
  <div class="product-add-page">
    <!-- 步骤指示器 -->
    <div class="steps-wrapper">
      <div class="step-item" :class="{ active: currentStep === 1, completed: currentStep > 1 }">
        <div class="step-icon">
          <i class="el-icon-check" v-if="currentStep > 1"></i>
          <span v-else>1</span>
        </div>
        <div class="step-label">填写商品信息</div>
      </div>
      <div class="step-item" :class="{ active: currentStep === 2, completed: currentStep > 2 }">
        <div class="step-icon">
          <i class="el-icon-check" v-if="currentStep > 2"></i>
          <span v-else>2</span>
        </div>
        <div class="step-label">填写商品促销</div>
      </div>
      <div class="step-item" :class="{ active: currentStep === 3, completed: currentStep > 3 }">
        <div class="step-icon">
          <i class="el-icon-check" v-if="currentStep > 3"></i>
          <span v-else>3</span>
        </div>
        <div class="step-label">填写商品属性</div>
      </div>
      <div class="step-item" :class="{ active: currentStep === 4 }">
        <div class="step-icon">
          <span>4</span>
        </div>
        <div class="step-label">设置商品规格</div>
      </div>
    </div>

    <!-- 错误提示 -->
    <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon @close="errorMessage = ''"
      style="margin-bottom: 15px;"></el-alert>

    <!-- 步骤内容区域 -->
    <div class="step-content">
      <!-- 步骤1：填写商品信息 -->
      <keep-alive>
        <BasicInfo v-if="currentStep === 1" :form-data="spuForm" :category-options="categoryOptions"
          :brand-options="brandOptions" :shipping-template-options="shippingTemplateOptions"
          @update-form="updateSpuForm" ref="basicInfoRef" />
      </keep-alive>

      <!-- 步骤2：填写商品促销 -->
      <keep-alive>
        <PromotionInfo v-if="currentStep === 2" :form-data="marketingForm" :tag-options="tagOptions"
          :promotion-options="promotionOptions" @update-form="updateMarketingForm" ref="promotionInfoRef" />
      </keep-alive>

      <!-- 步骤3：填写商品属性 -->
      <keep-alive>
        <AttributeInfo v-if="currentStep === 3" :form-data="attributeForm" :attribute-options="attributeOptions"
          @update-form="updateAttributeForm" ref="attributeInfoRef" />
      </keep-alive>

      <!-- 步骤4：设置商品规格 -->
      <keep-alive>
        <SkuInfo v-if="currentStep === 4" :sku-list="skuList" @update-sku-list="updateSkuList" @add-sku="addSku"
          @remove-sku="removeSku" ref="skuInfoRef" />
      </keep-alive>

      <!-- 预览区域 -->
      <div class="preview-area" v-if="showPreview">
        <ProductPreview :spu-form="spuForm" :sku-list="skuList" :marketing-form="marketingForm"
          :tag-options="tagOptions" :promotion-options="promotionOptions" />
      </div>
    </div>

    <!-- 步骤控制按钮 -->
    <div class="action-buttons">
      <el-button @click="prevStep" v-if="currentStep > 1" :disabled="isLoading">上一步</el-button>
      <el-button type="primary" @click="nextStep" v-if="currentStep < 4" :loading="isLoading">下一步</el-button>
      <el-button type="success" @click="submitForm" v-if="currentStep === 4" :loading="isSubmitting">提交</el-button>
      <el-button type="info" @click="togglePreview" :disabled="isLoading">{{ showPreview ? '隐藏预览' : '显示预览'
      }}</el-button>
    </div>

    <!-- 加载中遮罩 -->
    <div class="loading-mask" v-if="isLoading">
      <div class="loading-content">
        <i class="el-icon-loading"></i>
        <p>数据加载中...</p>
      </div>
    </div>
  </div>
</template>

<script>
import BasicInfo from './components/BasicInfo.vue';
import PromotionInfo from './components/PromotionInfo.vue';
import AttributeInfo from './components/AttributeInfo.vue';
import SkuInfo from './components/SkuInfo.vue';
import ProductPreview from './components/ProductPreview.vue';
import { debounce } from 'lodash-es';

export default {
  components: {
    BasicInfo,
    PromotionInfo,
    AttributeInfo,
    SkuInfo,
    ProductPreview
  },
  data() {
    return {
      currentStep: 1,
      showPreview: false,
      isLoading: false,
      isSubmitting: false,
      errorMessage: '',
      apiRequestQueue: [],
      spuForm: {
        name: "",
        category_id: [],
        brand_id: "",
        shipping_template_id: "",
        main_image: "",
        main_image_list: [],
        album_images: [],
        album_images_list: [],
        video: "",
        video_list: [],
        description: "",
        detail: "",
        status: 1,
        points: "0",
        growth_value: "0",
        point_limit: "0",
        is_preview: false,
        is_publish: false,
        is_new: false,
        is_recommend: false,
        services: [],
        detail_title: "",
        detail_desc: "",
        keywords: "",
        note: ""
      },
      skuList: [
        {
          sku_code: "",
          name: "",
          price: 0,
          market_price: 0,
          cost_price: 0,
          stock: 0,
          stock_warning: 10,
          weight: 0,
          volume: 0,
          spec_data: {},
          limit_per_order: null
        }
      ],
      marketingForm: {
        tags: [],
        promotions: [],
        presell_config: {
          is_presell: false,
          start_time: null,
          end_time: null,
          delivery_days: 7
        },
        member_priority: false,
        limit_per_member: 0
      },
      attributeForm: {},
      categoryOptions: [],
      brandOptions: [],
      shippingTemplateOptions: [],
      tagOptions: [],
      promotionOptions: [],
      attributeOptions: []
    };
  },
  created() {
    this.debouncedUpdateSpuForm = debounce(this.updateSpuForm, 500);
    this.debouncedUpdateMarketingForm = debounce(this.updateMarketingForm, 500);
    this.debouncedUpdateAttributeForm = debounce(this.updateAttributeForm, 500);
    this.debouncedUpdateSkuList = debounce(this.updateSkuList, 500);
    this.fetchInitialData();

    // 添加页面离开确认
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeDestroy() {
    // 清理事件监听和取消所有未完成的API请求
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
    this.cancelAllRequests();

    // 清理防抖函数
    if (this.debouncedUpdateSpuForm && this.debouncedUpdateSpuForm.cancel) {
      this.debouncedUpdateSpuForm.cancel();
    }
    if (this.debouncedUpdateMarketingForm && this.debouncedUpdateMarketingForm.cancel) {
      this.debouncedUpdateMarketingForm.cancel();
    }
    if (this.debouncedUpdateAttributeForm && this.debouncedUpdateAttributeForm.cancel) {
      this.debouncedUpdateAttributeForm.cancel();
    }
    if (this.debouncedUpdateSkuList && this.debouncedUpdateSkuList.cancel) {
      this.debouncedUpdateSkuList.cancel();
    }

    // 清理大对象引用，帮助垃圾回收
    this.spuForm = null;
    this.skuList = null;
    this.marketingForm = null;
    this.attributeForm = null;
    this.categoryOptions = null;
    this.brandOptions = null;
    this.shippingTemplateOptions = null;
    this.tagOptions = null;
    this.promotionOptions = null;
    this.attributeOptions = null;
  },
  methods: {
    handleBeforeUnload(e) {
      // 如果有未保存的数据，提示用户
      e.preventDefault();
      e.returnValue = '您有未保存的数据，确定要离开吗？';
    },
    cancelAllRequests() {
      // 取消所有未完成的API请求
      this.apiRequestQueue.forEach(cancel => {
        if (typeof cancel === 'function') {
          cancel();
        }
      });
      this.apiRequestQueue = [];
    },
    async fetchInitialData() {
      try {
        this.isLoading = true;
        this.errorMessage = '';

        // 并行请求数据以提高加载速度
        await Promise.all([
          this.fetchCategories(),
          this.fetchBrands(),
          this.fetchShippingTemplates(),
          this.fetchTags(),
          this.fetchPromotions()
        ]);
      } catch (error) {
        this.handleError(error, '加载初始数据失败');
      } finally {
        this.isLoading = false;
      }
    },
    fetchCategories() {
      return new Promise((resolve) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            this.categoryOptions = [
              {
                value: "1",
                label: "电子产品",
                children: [
                  {
                    value: "1-1",
                    label: "手机",
                    children: [
                      {
                        value: "1-1-1",
                        label: "智能手机",
                      },
                    ],
                  },
                ],
              }
            ];
            resolve();
          } catch (error) {
            this.handleError(error, '获取分类数据失败');
            resolve();
          }
        }, 500);
      });
    },
    fetchBrands() {
      return new Promise((resolve) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            this.brandOptions = [
              { id: "1", name: "苹果" },
              { id: "2", name: "三星" },
              { id: "3", name: "华为" }
            ];
            resolve();
          } catch (error) {
            this.handleError(error, '获取品牌数据失败');
            resolve();
          }
        }, 500);
      });
    },
    fetchShippingTemplates() {
      return new Promise((resolve) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            this.shippingTemplateOptions = [
              { id: "1", name: "包邮模板" },
              { id: "2", name: "按件计费" },
              { id: "3", name: "按重量计费" }
            ];
            resolve();
          } catch (error) {
            this.handleError(error, '获取运费模板失败');
            resolve();
          }
        }, 500);
      });
    },
    fetchTags() {
      return new Promise((resolve) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            this.tagOptions = [
              { id: "1", name: "热销", style_config: { color: "#ff4d4f" } },
              { id: "2", name: "新品", style_config: { color: "#52c41a" } },
              { id: "3", name: "推荐", style_config: { color: "#1890ff" } }
            ];
            resolve();
          } catch (error) {
            this.handleError(error, '获取标签数据失败');
            resolve();
          }
        }, 500);
      });
    },
    fetchPromotions() {
      return new Promise((resolve) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            this.promotionOptions = [
              { id: "1", name: "618大促", type: 1, discount_value: 8.5 },
              { id: "2", name: "满300减50", type: 5, threshold_value: 300, discount_value: 50 }
            ];
            resolve();
          } catch (error) {
            this.handleError(error, '获取促销活动失败');
            resolve();
          }
        }, 500);
      });
    },
    async fetchAttributes(categoryId) {
      try {
        this.isLoading = true;
        this.errorMessage = '';

        // 模拟API调用
        await new Promise((resolve) => {
          setTimeout(() => {
            try {
              this.attributeOptions = [
                {
                  id: "1",
                  name: "颜色",
                  type: 2, // 销售属性
                  input_type: "select",
                  options: [
                    { label: "黑色", value: "black" },
                    { label: "白色", value: "white" },
                    { label: "蓝色", value: "blue" }
                  ]
                },
                {
                  id: "2",
                  name: "内存",
                  type: 2, // 销售属性
                  input_type: "select",
                  options: [
                    { label: "64GB", value: "64gb" },
                    { label: "128GB", value: "128gb" },
                    { label: "256GB", value: "256gb" }
                  ]
                },
                {
                  id: "3",
                  name: "处理器",
                  type: 3, // 参数属性
                  input_type: "text"
                },
                {
                  id: "4",
                  name: "屏幕尺寸",
                  type: 3, // 参数属性
                  input_type: "text"
                },
                {
                  id: "5",
                  name: "特性",
                  type: 3, // 参数属性
                  input_type: "checkbox",
                  options: [
                    { label: "防水", value: "waterproof" },
                    { label: "防尘", value: "dustproof" },
                    { label: "快充", value: "fastcharge" }
                  ]
                }
              ];
              resolve();
            } catch (error) {
              this.handleError(error, '获取属性数据失败');
              resolve();
            }
          }, 500);
        });
      } catch (error) {
        this.handleError(error, '获取属性数据失败');
      } finally {
        this.isLoading = false;
      }
    },
    async nextStep() {
      if (this.currentStep < 4 && !this.isLoading) {
        try {
          this.isLoading = true;
          this.errorMessage = '';

          // 验证当前步骤表单
          try {
            await this.validateStep(this.currentStep);
          } catch (error) {
            this.handleError(error);
            this.isLoading = false;
            return;
          }

          // 特殊处理第一步完成后的操作
          if (this.currentStep === 1) {
            // 如果分类变更，重新获取属性
            if (this.spuForm.category_id && this.spuForm.category_id.length > 0) {
              try {
                const categoryId = this.spuForm.category_id[this.spuForm.category_id.length - 1];
                await this.fetchAttributes(categoryId);
              } catch (error) {
                this.handleError(error, '获取属性数据失败');
                // 即使获取属性失败，也允许继续下一步
              }
            }
          }

          // 进入下一步
          this.currentStep++;
        } catch (error) {
          this.handleError(error);
        } finally {
          this.isLoading = false;
        }
      }
    },
    prevStep() {
      if (this.currentStep > 1 && !this.isLoading) {
        this.currentStep--;
      }
    },
    async validateStep(step) {
      try {
        switch (step) {
          case 1:
            if (this.$refs.basicInfoRef) {
              await this.$refs.basicInfoRef.validate();
            } else {
              if (!this.validateBasicInfo()) {
                throw new Error('基本信息验证失败');
              }
            }
            break;
          case 2:
            try {
              if (this.$refs.promotionInfoRef) {
                await this.$refs.promotionInfoRef.validate();
              } else {
                throw new Error('促销信息组件未正确加载，请刷新页面重试');
              }
            } catch (error) {
              throw error; // 直接抛出原始错误，保留完整的错误信息
            }
            break;
          case 3:
            if (this.$refs.attributeInfoRef) {
              await this.$refs.attributeInfoRef.validate();
            }
            break;
          case 4:
            if (this.$refs.skuInfoRef) {
              await this.$refs.skuInfoRef.validate();
            } else {
              if (!this.validateSkuInfo()) {
                throw new Error('SKU信息验证失败');
              }
            }
            break;
        }
        return true;
      } catch (error) {
        throw error;
      }
    },
    validateBasicInfo() {
      // 基本信息验证
      if (!this.spuForm.name) {
        this.$message.error('请输入商品名称');
        return false;
      }
      if (!this.spuForm.category_id || this.spuForm.category_id.length === 0) {
        this.$message.error('请选择商品分类');
        return false;
      }
      return true;
    },
    validateSkuInfo() {
      // 验证SKU信息
      if (this.skuList.length === 0) {
        this.$message.error('至少需要添加一个SKU');
        return false;
      }

      for (let i = 0; i < this.skuList.length; i++) {
        const sku = this.skuList[i];
        if (!sku.sku_code) {
          this.$message.error(`第${i + 1}个SKU的编码不能为空`);
          return false;
        }
        if (!sku.name) {
          this.$message.error(`第${i + 1}个SKU的名称不能为空`);
          return false;
        }
        if (sku.price <= 0) {
          this.$message.error(`第${i + 1}个SKU的销售价格必须大于0`);
          return false;
        }
      }
      return true;
    },
    updateSpuForm(formData) {
      try {
        // 使用Vue.set确保响应式更新
        Object.keys(formData).forEach(key => {
          this.$set(this.spuForm, key, formData[key]);
        });
      } catch (error) {
        this.handleError(error, '更新商品信息失败');
      }
    },
    updateMarketingForm(formData) {
      try {
        // 移除多余的日志输出
        if (!formData) {
          return;
        }

        // 直接一次性更新，减少响应式更新次数
        this.marketingForm = {
          ...this.marketingForm,
          ...formData,
          presell_config: formData.presell_config ? {
            ...this.marketingForm.presell_config,
            ...formData.presell_config
          } : this.marketingForm.presell_config
        };
      } catch (error) {
        this.handleError(error, '更新促销信息失败');
      }
    },
    updateAttributeForm(formData) {
      try {
        // 使用Vue.set确保响应式更新
        this.attributeForm = { ...formData };
      } catch (error) {
        this.handleError(error, '更新属性信息失败');
      }
    },
    updateSkuList(skuList) {
      try {
        // 限制SKU数量，防止生成过多导致页面崩溃
        if (skuList.length > 100) {
          this.$confirm('生成的SKU数量过多，可能导致页面性能问题，是否继续?', '警告', {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.skuList = [...skuList];
          }).catch(() => {
            // 用户取消，保持原状态
          });
        } else {
          this.skuList = [...skuList];
        }
      } catch (error) {
        this.handleError(error, '更新SKU列表失败');
      }
    },
    addSku() {
      try {
        // 限制SKU数量，防止添加过多导致页面崩溃
        if (this.skuList.length >= 100) {
          this.$message.warning('SKU数量已达上限(100个)，无法继续添加');
          return;
        }

        this.skuList.push({
          sku_code: "",
          name: "",
          price: 0,
          market_price: 0,
          cost_price: 0,
          stock: 0,
          stock_warning: 10,
          weight: 0,
          volume: 0,
          spec_data: {},
          limit_per_order: null
        });
      } catch (error) {
        this.handleError(error, '添加SKU失败');
      }
    },
    removeSku(index) {
      try {
        if (index >= 0 && index < this.skuList.length) {
          this.skuList.splice(index, 1);
        }
      } catch (error) {
        this.handleError(error, '删除SKU失败');
      }
    },
    togglePreview() {
      this.showPreview = !this.showPreview;
    },
    async submitForm() {
      if (this.isSubmitting) return;

      try {
        this.isSubmitting = true;
        this.errorMessage = '';

        // 表单提交前验证
        await this.validateAllSteps();

        // 组装提交数据
        const submitData = this.prepareSubmitData();
        // 这里应该调用API保存数据
        await this.mockApiSubmit(submitData);

        this.$message.success("商品添加成功！");

        // 提交成功后可以跳转到商品列表页
        // this.$router.push('/product/list');
      } catch (error) {
        this.handleError(error, '提交表单失败');
      } finally {
        this.isSubmitting = false;
      }
    },
    prepareSubmitData() {
      // 深拷贝数据，避免引用问题
      return {
        spu: JSON.parse(JSON.stringify(this.spuForm)),
        skuList: JSON.parse(JSON.stringify(this.skuList)),
        marketing: JSON.parse(JSON.stringify(this.marketingForm)),
        attributes: JSON.parse(JSON.stringify(this.attributeForm))
      };
    },
    mockApiSubmit(data) {
      // 模拟API提交
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve();
        }, 1000);
      });
    },
    async validateAllSteps() {
      // 验证所有步骤
      for (let step = 1; step <= 4; step++) {
        try {
          await this.validateStep(step);
        } catch (error) {
          this.currentStep = step; // 跳转到出错的步骤
          throw error;
        }
      }
    },
    handleError(error, defaultMessage = '操作失败') {
      // 提取错误信息
      let errorMsg = defaultMessage;
      if (error) {
        if (typeof error === 'string') {
          errorMsg = error;
        } else if (error.message) {
          errorMsg = error.message;
        }
      }

      // 设置错误消息
      this.errorMessage = errorMsg;

      // 显示错误提示
      this.$message.error(this.errorMessage);
    },
    // 获取当前步骤对应的组件名称，用于调试
    getStepComponentName() {
      switch (this.currentStep) {
        case 1: return 'BasicInfo';
        case 2: return 'PromotionInfo';
        case 3: return 'AttributeInfo';
        case 4: return 'SkuInfo';
        default: return 'Unknown';
      }
    }
  }
};
</script>

<style scoped>
.product-add-page {
  padding: 20px;
  position: relative;
}

.steps-wrapper {
  display: flex;
  margin-bottom: 30px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.step-item {
  flex: 1;
  text-align: center;
  position: relative;
}

.step-item:not(:last-child)::after {
  content: '';
  position: absolute;
  top: 20px;
  right: 0;
  width: 100%;
  height: 1px;
  background: #e0e0e0;
  z-index: 1;
}

.step-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f0f0;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 10px;
  position: relative;
  z-index: 2;
  font-weight: bold;
}

.step-label {
  color: #999;
  font-size: 14px;
}

.step-item.active .step-icon {
  background: #67c23a;
  color: white;
}

.step-item.active .step-label {
  color: #67c23a;
  font-weight: bold;
}

.step-item.completed .step-icon {
  background: #67c23a;
  color: white;
}

.step-content {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  min-height: 400px;
  position: relative;
}

.preview-area {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 100%;
  background: #f9f9f9;
  border-left: 1px solid #eee;
  padding: 15px;
  overflow-y: auto;
  z-index: 10;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-content {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.loading-content i {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 10px;
}
</style>
